package controllers;

import java.util.HashMap;
import java.util.Map;

import play.cache.Cache;
import play.mvc.After;
import play.mvc.Before;

import models.Persona;

import services.ServicePersonas;

public class Security extends Secure.Security{
	private static Map scache;
	static boolean authenticate(String username, String password) {
		Persona user = ServicePersonas.validarUsuario(username);
		if (user != null && user.getDeClave().equals(password)) {
			scache = new HashMap();
			scache.put("coUsuario", user);
			scache.put("deUsuario", username);			
			scache.put("sessionID", session.getId());			
			Cache.set("session_" + session.getId(), scache, "60mn");			
			return true;
		}
		return false;
	}	
	
	@Before
	static void getMenu() {
		if (Cache.get("session_"+session.getId(),Map.class) != null) {
			Map cacheUser = Cache.get("session_"+session.getId(),Map.class);
			renderArgs.put("menuUser", cacheUser.get("menu"));
			renderArgs.put("idpersona", cacheUser.get("coPersona"));
			renderArgs.put("deUsuario",cacheUser.get("deUsuario"));
		}
	}
	
	@After
	static void reGenerarMenu() throws Throwable{
		if(Cache.get("session_"+session.getId(),Map.class) != null){
			Map cacheUser = Cache.get("session_"+session.getId(),Map.class);
			Cache.set("session_" + session.getId(), cacheUser, "60mn");			
		}else{
			Secure.logout();
		}
	}
}
